package com.taotao.sso.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

@Service
public class RedisService {

	@Autowired(required=false)
	private ShardedJedisPool redisPool;
	
	private <T> T execute(Function<ShardedJedis, T> fun){
		ShardedJedis shardedJedis = null;
		try {
			shardedJedis = redisPool.getResource();
			T t = fun.callback(shardedJedis);
			return t;
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(shardedJedis != null) {
				shardedJedis.close();
			}
		}
		return null;
	}
	
	public String set(final String key, final String value){
		return this.execute(new Function<ShardedJedis, String>(){
			@Override
			public String callback(ShardedJedis jedis) {
				return jedis.set(key, value);
			}
		});
	}
	
	public String get(final String key){
		return this.execute(new Function<ShardedJedis, String>(){

			@Override
			public String callback(ShardedJedis jedis) {
				 
				return jedis.get(key);
			}
			
		});
	}
	
	public Long del(final String key){
		return this.execute(new Function<ShardedJedis, Long>(){

			@Override
			public Long callback(ShardedJedis e) {

				return e.del(key);
			}
			
		});
	}
	
	public Long expire(final String key, final int seconds){
		return this.execute(new Function<ShardedJedis, Long>(){

			@Override
			public Long callback(ShardedJedis e) {
				return e.expire(key, seconds);
			}
			
		});
	}
	
	public String set(final String key, final String value, final int seconds){
		return this.execute(new Function<ShardedJedis, String>(){
			@Override
			public String callback(ShardedJedis jedis) {
				String result = jedis.set(key, value);
				jedis.expire(key, seconds);
				return result;
			}
		});
	}
}
